<template>
  <el-upload class="upload-demo" ref="upload" :accept="accept" action="#" :on-remove="handleRemove"
    :on-change="handleChange" :before-upload="handleBeforeUpload" :on-exceed="handleExceed" :limit="1"
    :http-request="handleHttpRequest" :file-list="fileList">
    <el-button slot="trigger" size="mini" type="primary" class="is-thin">选取文件</el-button>
  </el-upload>
</template>

<script>
import Emitter from 'element-ui/src/mixins/emitter'
export default {
  name: 'yc-upload-file',
  mixins: [Emitter],
  inject: ['elForm'],
  props: {
    value: {
      type: [String, Array, Object, File]
    },
    fileSize: {
      type: Number,
      default: 200
    },
    accept: {
      type: String,
      default: ''
    },
    uploadFunction: {
      type: Function
    }
  },
  watch: {
    value: {
      handler () {
        this.handleResetCurrentValue()
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    model: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  data () {
    return {
      fileList: [],
      refreshList: true
    }
  },
  created () {

  },
  methods: {
    handleResetCurrentValue () {
      if (this.value === '') {
        this.fileList = []
      } else if (this.$_.isString(this.value) && this.value !== '' && this.fileList.length === 0 && this.refreshList) {
        var fileName = this.value.substring(this.value.lastIndexOf('/') + 1)
        this.fileList.push({
          name: fileName,
          url: this.value
        })
      }
    },
    checkLimit (file) {
      let result = true
      var fileEx = file.name.substring(file.name.lastIndexOf('.'))
      if (this.accept !== '' && this.accept.indexOf(fileEx.toLowerCase()) < 0) {
        this.$message.error(`文件格式有误,只能上传${this.accept}`)
        return false
      }
      if (file.size > this.fileSize * 1024 * 1024) {
        this.$message.error(`文件大小不能超过${this.fileSize}MB`)
        result = false
      }
      return result
    },
    handleRemove () {
      this.$refs.upload.abort()
      this.model = ''
      this.fileList = []
    },
    handleChange (file) {
    },
    handleBeforeUpload (file) {

    },
    handleExceed (files, fileList) {
    },
    handleHttpRequest (params) {
      const file = params.file
      var isOk = this.checkLimit(file)
      if (!isOk) {
        params.onError()
        return
      }
      if (this.uploadFunction) {
        var config = {
          onUploadProgress: (progressEvent) => {
            let num = progressEvent.loaded / progressEvent.total * 100 | 0 // 百分比
            params.onProgress({ percent: num })
          }
        }
        this.uploadFunction(file, config).then(res => {
          var { code, data } = res
          if (code === 200) {
            this.refreshList = false
            file.url = data
            this.model = data
            if (this.elForm) {
              this.elForm.validateField(this.$attrs.prop)
            }
            params.onSuccess()
          } else {
            params.onError()
          }
        }).catch(() => {
          params.onError()
        })
      }
    }
  }
}
</script>
